package com.luyuan.crm.member.web.provider;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Customer;
import com.luyuan.crm.member.service.CustomerService;
import com.luyuan.crm.user.Party;
import com.luyuan.crm.user.service.PartyService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.components.security.model.Role;
import com.ruijie.foundation.security.AppUserContext;

@Component("customerMoblieProvider")
public class CustomerMoblieProvider {
    @Resource(name = "customerService")
    private CustomerService customerService;

    @Resource(name = "partyService")
    private PartyService partyService;

    public List<Customer> getSuggestionItems(Object arg) {
        String s = String.valueOf(arg) + "%";
        Criterion criterion = Restrictions.or(Restrictions.like("mobile", s), Restrictions.like("name", s));

        // 归属分公司
        AppUser appUser = (AppUser) AppUserContext.getCurrentUser();
        Set<Role> roles = appUser.getRoles();
        for (Role role : roles) {
            if ("总经理".equals(role.getRoleName())) {
                // 总经理查询所有数据
                break;
            }

            // 其它人，只能查本分公司的数据
            Party party = partyService.getByAppUser(appUser);
            criterion = Restrictions.and(Restrictions.eq("branchOffice", party.getBranchOffice()), criterion);
        }

        List<Customer> members = customerService.findBy(criterion, 10);
        List<Customer> result = new ArrayList<Customer>(10);
        for (Customer member : members) {
            Customer m = new Customer();
            m.setId(member.getId());
            m.setName(member.getName());
            m.setMobile(member.getMobile());
            result.add(m);
        }
        return result;
    }
}
